from django.contrib import admin
from siteupdate.models import Update
from django.conf.urls.defaults import *
from django.http import HttpResponse
from siteupdate.settings import UPDATE_POSTCOMMAND, UPDATE_SHELL
from django.utils.translation import ugettext as _
import subprocess

class UpdateAdmin(admin.ModelAdmin):
    exclude = ('user', 'log',)
    list_display = ('user', 'updated_at', 'description',)
    
    def save_model(self, request, object, form, change):
        if not object.user:
            object.user = request.user
            request.session['postprocess'] = True
        object.save()

    def get_urls(self):
        urls = admin.ModelAdmin.get_urls(self)
        customurls = patterns('',
            url(r'^postprocess.js', self.postprocess, name='siteupdate_postprocess'),
            url(r'^postprocess_execute.js', self.postprocess_execute, name='siteupdate_postprocess_execute'),
        )
        return customurls + urls

    def postprocess(self, request):
        if request.session.get('postprocess'):
            request.session['postprocess'] = False
            if UPDATE_POSTCOMMAND:
                return HttpResponse("""
                    alert('%s');
                    setTimeout(function() {
                        var elem = document.createElement('SCRIPT');
                        elem.src = 'postprocess_execute.js';
                        elem.type = 'text/javascript';
                        document.body.appendChild(elem);
                    }, 2000);
                """ % _('Starting postprocessing, server may not respond for a few seconds...'), 'text/javascript')
        return HttpResponse('/* No postprocessing required */', 'text/javscript')
    
    def postprocess_execute(self, request):
        if UPDATE_POSTCOMMAND:
            output = subprocess.Popen(UPDATE_POSTCOMMAND, executable=UPDATE_SHELL, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
            if output[1]:
                request.user.message_set.create(message=_('Post process script returned a error: ') + output[1])
        return HttpResponse('/* done */', 'text/javascript')

admin.site.register(Update, UpdateAdmin)
